<template>
  <view class="printer-select">
    <view class="ble-list-warp">
      <view class="ble-list-label">
        <text>已连接设备</text>
      </view>
      <mz-list>
        <mz-list-item
          v-for="(item) in connectList"
          :key="item.deviceId"
          :title="item.name||item.deviceId"
          :note="item.deviceId"
          @click.native="handleClickBle(item)"
        >
          <template v-slot:right>
            <text class="connect-tag">已连接</text>
          </template>
        </mz-list-item>
      </mz-list>
      <!-- <form>
        <form-item
          v-for="(item,index) in connectList"
          :key="index"
          :label="item.name||item.deviceId"
          :show-arrow="false"
          text-align="right"
          @click.native="handleClickBle(item)"
        >
          <template>
            <text class="connect-tag">已连接</text>
          </template>
        </form-item>
      </form>-->
    </view>
    <view class="ble-list-warp">
      <view class="ble-list-label">
        <text>未连接设备</text>
      </view>
      <mz-list>
        <mz-list-item
          v-for="(item,index) in newBleList"
          :key="index"
          :title="item.name||item.deviceId"
          :note="item.deviceId"
          @click.native="handleClickBle(item)"
        >
          <template v-slot:right>
            <text class="rssi-wrap">信号强度: {{ item.RSSI }}dBm ({{ Math.max(100+item.RSSI,0) }}%)</text>
          </template>
        </mz-list-item>
      </mz-list>
      <!-- <form>
        <form-item
          v-for="(item,index) in newBleList"
          :key="index"
          :label="item.name||item.deviceId"
          :show-arrow="false"
          text-align="right"
          @click.native="handleClickBle(item)"
        ></form-item>
      </form>-->
    </view>
    <view v-if="loading" class="loading-wrap">
      <!-- <text>搜索中</text> -->
      <uni-load-more status="loading" :content-text="contentText"></uni-load-more>
    </view>
    <!-- <FooterButton @click.native="printTest">打印测试</FooterButton> -->
  </view>
</template>

<script>
import { mapState, mapMutations, mapGetters } from "vuex";
import { orderTestData } from "../../utils/printerData";
import FooterButton from "../../components/public/Button/FooterButton.vue";
import Form from "../../components/public/Form/index.vue";
import FormItem from "../../components/public/FormItem/index.vue";
let timer = null;
export default {
  components: { FooterButton, Form, FormItem },
  data() {
    return {
      list: [],
      num: 1,
      loading: false,
      contentText: {
        // contentdown: "上拉显示更多",
        contentrefresh: "搜索中..."
        // contentnomore: "暂无更多"
      }
    };
  },
  computed: {
    ...mapState({
      bleList: state => state.printer.bleList
    }),
    ...mapGetters({
      connectBleIds: "connectBleIds"
    }),
    // 已连接设备
    connectList() {
      return this.bleList.filter(v => v.connected);
    },
    // 新的未连接设备
    newBleList() {
      return this.list
        .filter(v => !this.checkConnect(v.deviceId))
        .sort((a, b) => Math.max(100 + b.RSSI, 0) - Math.max(100 + a.RSSI, 0));
    }
  },
  onLoad() {
    this.search();
  },
  onNavigationBarButtonTap(data) {
    this.search();
  },
  onBackPress() {
    this.$printerUtil.stopSearch();
  },
  methods: {
    ...mapMutations({
      ADD_MEW_BLUETOOTH: "ADD_MEW_BLUETOOTH",
      REMOVE_BLUETOOTH: "REMOVE_BLUETOOTH"
    }),
    printTest() {
      this.bleList.forEach(ble => {
        this.$printerUtil.print({
          ...ble,
          buff: orderTestData(),
          num: this.num,
          success: () => {},
          fail: e => {
            console.log("打印错误", e);
          }
        });
      });
    },
    // 检查是否连接
    checkConnect(deviceId) {
      let index = this.connectBleIds.indexOf(deviceId);
      return index > -1 && this.bleList[index].connected;
    },
    async search() {
      clearTimeout(timer);
      if (this.loading) await this.$printerUtil.stopSearch();
      this.list = [];
      this.loading = true;
      this.$printerUtil.search({
        search: list => {
          this.list = list;
        },
        finish: () => {
          this.loading = false;
        }
      });
      // 10s后停止搜索
      timer = setTimeout(() => {
        this.$printerUtil.stopSearch().finally(() => {
          this.loading = false;
        });
      }, 1000 * 10);
    },
    handleClickBle(item) {
      let deviceId = item.deviceId;
      if (this.checkConnect(deviceId)) {
        this.disconnect(deviceId);
      } else {
        this.connect(item);
      }
      this.$printerUtil.stopSearch();
    },
    // 连接蓝牙
    connect(item) {
      uni.showLoading({
        title: "连接中",
        mask: true
      });
      this.$printerUtil.bind(
        {
          ...item
        },
        res => {
          uni.hideLoading();
          if (!res.state) {
            uni.showToast({
              icon: "none",
              title: "连接成功"
            });
          } else {
            uni.showToast({
              icon: "none",
              title: "连接失败,请检查设备是否可用或重新连接"
            });
          }
        }
      );
    },
    // 断开蓝牙
    disconnect(deviceId) {
      uni.showLoading({
        title: "断开中",
        mask: true
      });
      this.$printerUtil.disconnect(
        {
          deviceId
        },
        res => {
          uni.hideLoading();
          this.REMOVE_BLUETOOTH(deviceId);
          uni.showToast({
            icon: "none",
            title: "断开连接"
          });
        }
      );
    }
  }
};
</script>
<style lang="scss">
page {
  background-color: $uni-bg-color-grey;
}
.printer-select {
  padding-bottom: 100rpx;
  .ble-list-warp {
    background-color: #ffffff;
    margin-bottom: 24rpx;
    .ble-list-label {
      padding: 20rpx $form-item-left;
      // padding-bottom: 10rpx;
    }
    .connect-tag {
      color: $uni-color-primary;
    }
    .rssi-wrap {
      font-size: 24rpx;
      color: $uni-text-color-grey;
    }
  }
  .loading-wrap {
    padding: 10rpx 0;
    text-align: center;
  }
}
</style>